package cn.dogger.thread.config;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dogger
 * 2022/11/14 16:50
 */
public class NamedThreadFactory  implements ThreadFactory {

    /**
     * 线程组
     */
    private final ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();;

    /**
     * 线程数
     * 初始值为1
     */
    private final AtomicInteger threadNumber = new AtomicInteger(1);

    /**
     * 线程名称
     */
    public String namePrefix;

    /**
     * 线程命名
     * @param name
     */
    public NamedThreadFactory(String name){
        if (null==name || "".equals(name.trim())){
            name = "pool";
        }

         //线程工厂的编号,初始值为1
        AtomicInteger poolNumber = new AtomicInteger(1);
        //xxx-1-thread-
        namePrefix = name +"-"+
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(threadGroup, r,
                namePrefix + threadNumber.getAndIncrement(),
                0);
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
